import { COLORS, GAME_STATUS, STORAGE_KEYS, UNDO_LIMIT, BOARD_CONFIG } from './constants.js';
import { Board } from './board.js';
import { ChessAI } from './ai.js';

// 游戏类
export class XiangqiGame {
    constructor() {
        this.board = new Board();
        this.ai = new ChessAI();
        this.status = GAME_STATUS.READY;
        this.currentTurn = COLORS.RED;
        this.gameMode = 'human-ai'; // 默认人机对战
        this.selectedPiece = null;
        this.possibleMoves = [];
        this.undoCount = 0;
        this.scores = {
            [COLORS.RED]: 0,
            [COLORS.BLACK]: 0
        };
        this.moveCount = 0;
        this.winner = null;
        
        // 加载保存的分数
        this.loadScores();
    }
    
    // 开始新游戏
    start() {
        this.board.reset();
        this.status = GAME_STATUS.PLAYING;
        this.currentTurn = COLORS.RED;
        this.selectedPiece = null;
        this.possibleMoves = [];
        this.undoCount = 0;
        this.moveCount = 0;
        this.winner = null;
        
        // 如果是人机对战且AI先行（黑方），AI先下棋
        if (this.gameMode === 'human-ai' && this.currentTurn === COLORS.BLACK) {
            setTimeout(() => this.makeAIMove(), 500);
        }
        
        return true;
    }
    
    // 设置游戏模式
    setGameMode(mode) {
        if (this.status === GAME_STATUS.PLAYING) {
            return false; // 游戏进行中，无法更改模式
        }
        
        this.gameMode = mode;
        return true;
    }
    
    // 设置AI难度
    setAIDifficulty(difficulty) {
        this.ai.setDifficulty(difficulty);
        return true;
    }
    
    // 暂停游戏
    pause() {
        if (this.status === GAME_STATUS.PLAYING) {
            this.status = GAME_STATUS.PAUSED;
            return true;
        }
        return false;
    }
    
    // 继续游戏
    resume() {
        if (this.status === GAME_STATUS.PAUSED) {
            this.status = GAME_STATUS.PLAYING;
            
            // 如果是AI回合且游戏暂停后恢复，AI继续下棋
            if (this.gameMode === 'human-ai' && this.currentTurn === COLORS.BLACK) {
                setTimeout(() => this.makeAIMove(), 500);
            }
            
            return true;
        }
        return false;
    }
    
    // 重新开始游戏
    restart() {
        return this.start();
    }
    
    // 悔棋
    undo() {
        if (this.status !== GAME_STATUS.PLAYING || this.board.moveHistory.length === 0) {
            return false;
        }
        
        // 检查悔棋次数限制
        if (this.undoCount >= UNDO_LIMIT) {
            return false;
        }
        
        // 撤销两步（自己和对方各一步），除非是第一步
        let undoSucceed = false;
        
        // 首先撤销当前玩家的最后一步
        if (this.board.undoMove()) {
            this.undoCount++;
            undoSucceed = true;
            
            // 如果是人机对战，再撤销AI的一步
            if (this.gameMode === 'human-ai' && this.board.moveHistory.length > 0) {
                if (this.board.undoMove()) {
                    this.undoCount++;
                }
            }
            
            // 恢复回合到红方
            this.currentTurn = COLORS.RED;
            this.selectedPiece = null;
            this.possibleMoves = [];
        }
        
        return undoSucceed;
    }
    
    // 选择棋子
    selectPiece(row, col) {
        if (this.status !== GAME_STATUS.PLAYING) {
            return false;
        }
        
        // 检查是否是当前玩家的回合
        const piece = this.board.getPieceAt(row, col);
        
        // 如果点击的是自己的棋子
        if (piece && piece.color === this.currentTurn) {
            this.selectedPiece = { row, col, piece };
            this.possibleMoves = piece.getPossibleMoves(this.board);
            return true;
        }
        
        // 如果已经选中了棋子，尝试移动
        if (this.selectedPiece) {
            return this.movePiece(this.selectedPiece.row, this.selectedPiece.col, row, col);
        }
        
        return false;
    }
    
    // 移动棋子
    movePiece(fromRow, fromCol, toRow, toCol) {
        if (this.status !== GAME_STATUS.PLAYING) {
            return false;
        }
        
        // 检查是否是当前玩家的回合
        const piece = this.board.getPieceAt(fromRow, fromCol);
        if (!piece || piece.color !== this.currentTurn) {
            return false;
        }
        
        // 执行移动
        const capturedPiece = this.board.movePiece(fromRow, fromCol, toRow, toCol);
        
        if (capturedPiece) {
            this.moveCount = 0; // 重置无吃子步数
        } else {
            this.moveCount++; // 增加无吃子步数
        }
        
        // 清除选中状态
        this.selectedPiece = null;
        this.possibleMoves = [];
        
        // 检查游戏状态
        if (this.checkGameStatus()) {
            return true;
        }
        
        // 切换回合
        this.currentTurn = this.currentTurn === COLORS.RED ? COLORS.BLACK : COLORS.RED;
        
        // 如果是人机对战且轮到AI（黑方）
        if (this.gameMode === 'human-ai' && this.currentTurn === COLORS.BLACK) {
            setTimeout(() => this.makeAIMove(), 500);
        }
        
        return true;
    }
    
    // AI下棋
    makeAIMove() {
        if (this.status !== GAME_STATUS.PLAYING || this.currentTurn !== COLORS.BLACK) {
            return;
        }
        
        // 获取AI的最佳移动
        const move = this.ai.chooseMove(this.board, COLORS.BLACK);
        
        if (move) {
            // 执行AI移动
            const capturedPiece = this.board.movePiece(move.fromRow, move.fromCol, move.toRow, move.toCol);
            
            if (capturedPiece) {
                this.moveCount = 0;
            } else {
                this.moveCount++;
            }
            
            // 检查游戏状态
            if (this.checkGameStatus()) {
                return;
            }
            
            // 切换回合到玩家
            this.currentTurn = COLORS.RED;
        }
    }
    
    // 检查游戏状态
    checkGameStatus() {
        // 检查红方是否被将死
        if (this.board.isCheckmated(COLORS.RED)) {
            this.status = GAME_STATUS.OVER;
            this.winner = COLORS.BLACK;
            this.updateScores(COLORS.BLACK);
            return true;
        }
        
        // 检查黑方是否被将死
        if (this.board.isCheckmated(COLORS.BLACK)) {
            this.status = GAME_STATUS.OVER;
            this.winner = COLORS.RED;
            this.updateScores(COLORS.RED);
            return true;
        }
        
        // 检查是否和棋
        if (this.board.isDraw()) {
            this.status = GAME_STATUS.DRAW;
            this.winner = null;
            this.updateScores(null); // 和棋各得0.5分
            return true;
        }
        
        // 检查无吃子步数是否达到和棋条件
        if (this.moveCount >= 100) { // 50回合无吃子
            this.status = GAME_STATUS.DRAW;
            this.winner = null;
            this.updateScores(null);
            return true;
        }
        
        return false;
    }
    
    // 更新分数
    updateScores(winner) {
        if (winner === COLORS.RED) {
            this.scores[COLORS.RED] += 1;
        } else if (winner === COLORS.BLACK) {
            this.scores[COLORS.BLACK] += 1;
        } else { // 和棋
            this.scores[COLORS.RED] += 0.5;
            this.scores[COLORS.BLACK] += 0.5;
        }
        
        // 保存分数
        this.saveScores();
    }
    
    // 保存分数
    saveScores() {
        try {
            localStorage.setItem(STORAGE_KEYS.SCORES, JSON.stringify(this.scores));
        } catch (e) {
            console.error('无法保存分数:', e);
        }
    }
    
    // 加载分数
    loadScores() {
        try {
            const savedScores = localStorage.getItem(STORAGE_KEYS.SCORES);
            if (savedScores) {
                this.scores = JSON.parse(savedScores);
            }
        } catch (e) {
            console.error('无法加载分数:', e);
            // 使用默认分数
            this.scores = {
                [COLORS.RED]: 0,
                [COLORS.BLACK]: 0
            };
        }
    }
    
    // 保存游戏进度
    saveProgress() {
        try {
            const progress = {
                board: this.board.getBoardState(),
                status: this.status,
                currentTurn: this.currentTurn,
                gameMode: this.gameMode,
                moveCount: this.moveCount,
                moveHistory: this.board.moveHistory
            };
            
            localStorage.setItem(STORAGE_KEYS.GAME_PROGRESS, JSON.stringify(progress));
            return true;
        } catch (e) {
            console.error('无法保存游戏进度:', e);
            return false;
        }
    }
    
    // 加载游戏进度
    loadProgress() {
        try {
            const savedProgress = localStorage.getItem(STORAGE_KEYS.GAME_PROGRESS);
            if (!savedProgress) {
                return false;
            }
            
            const progress = JSON.parse(savedProgress);
            
            // 恢复游戏状态
            this.status = progress.status;
            this.currentTurn = progress.currentTurn;
            this.gameMode = progress.gameMode;
            this.moveCount = progress.moveCount;
            
            // 注意：完整恢复棋盘状态需要更复杂的逻辑
            // 这里简化处理，直接重新开始游戏
            this.start();
            
            return true;
        } catch (e) {
            console.error('无法加载游戏进度:', e);
            return false;
        }
    }
    
    // 获取游戏状态信息
    getGameInfo() {
        return {
            status: this.status,
            currentTurn: this.currentTurn,
            gameMode: this.gameMode,
            scores: this.scores,
            winner: this.winner,
            moveCount: this.moveCount,
            isInCheck: {
                [COLORS.RED]: this.board.isInCheck(COLORS.RED),
                [COLORS.BLACK]: this.board.isInCheck(COLORS.BLACK)
            }
        };
    }
    
    // 绘制游戏状态
    draw(ctx) {
        // 绘制棋盘和棋子
        this.board.draw(ctx);
        
        // 绘制选中状态
        if (this.selectedPiece) {
            this.board.drawSelectedPiece(ctx, this.selectedPiece.row, this.selectedPiece.col);
            this.board.drawPossibleMoves(ctx, this.possibleMoves);
        }
        
        // 绘制将军提示
        const info = this.getGameInfo();
        if (info.isInCheck[COLORS.RED] || info.isInCheck[COLORS.BLACK]) {
            const generalColor = info.isInCheck[COLORS.RED] ? COLORS.RED : COLORS.BLACK;
            const general = this.board.findGeneral(generalColor);
            if (general) {
                this.drawCheckWarning(ctx, general.row, general.col);
            }
        }
    }
    
    // 绘制将军警告
    drawCheckWarning(ctx, row, col) {
        const x = BOARD_CONFIG.MARGIN + col * BOARD_CONFIG.CELL_SIZE;
        const y = BOARD_CONFIG.MARGIN + row * BOARD_CONFIG.CELL_SIZE;
        const radius = BOARD_CONFIG.CELL_SIZE * 0.5;
        
        // 绘制闪烁的红色边框表示将军
        ctx.strokeStyle = '#FF0000';
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.stroke();
    }
}